<template>
  <div class="app-container">
    <el-card class="main-content">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建时间" prop="dateCreated">
        <el-date-picker clearable
          v-model="queryParams.dateCreated"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务名" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          placeholder="请输入任务名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消息主题" prop="smsSubjecte">
        <el-input
          v-model="queryParams.smsSubjecte"
          placeholder="请输入消息主题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="enableFlag">
        <el-select v-model="queryParams.enableFlag" placeholder="请选择任务状态" clearable>
          <el-option v-for="dict in dict.type.task_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="执行时间" prop="startAt">
        <el-date-picker clearable
          v-model="queryParams.startAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择执行时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="创建人" prop="createdName">
        <el-input
          v-model="queryParams.createdName"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-caret-right"
          size="mini"
          @click="handleStartTask"
        >手动执行</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="smstaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-if="false" label="任务id" align="center" prop="id" />
      <el-table-column label="任务名" align="center" prop="jobName" />
      <el-table-column label="创建时间" align="center" prop="dateCreated" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dateCreated, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="dateUpdated" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dateUpdated, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="消息主题" align="center" prop="smsSubjecte" />
      <el-table-column label="消息内容" align="center" prop="smsContent" />
      <el-table-column  v-if="false" label="消息内容html" align="center" prop="smsHtml" />
      <el-table-column label="任务状态" align="center" prop="enableFlag" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_state" :value="scope.row.enableFlag" />
        </template>
      </el-table-column>
      <el-table-column v-if="false" label="附带的参数，json格式" align="center" prop="param" />
      <el-table-column label="执行时间" align="center" prop="startAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="false"  label="会员id" align="center" prop="memberId" />
      <el-table-column label="创建人" align="center" prop="createdName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleShowRecord(scope.row)"
          >查看记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改消息群发任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <div class="tip">
        <p class="text-sm text-blue-700">
          <span class="font-bold">1.</span> 同一个企业每个自然月内仅可对一个客户发送4条消息，超过限制的用户将会被惩罚
        </p>
        <p class="text-sm text-blue-700">
          <span class="font-bold">2.</span> 单次群发任务中，若设置了文字+图片、文字+网页或文字+小程序的群发内容，仅会占用一次群发机会
        </p>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务名" prop="jobName">
          <el-input v-model="form.jobName" placeholder="请输入任务名" />
        </el-form-item>
        <el-form-item label="消息通道" prop="smsType">
          <el-select v-model="form.smsType" placeholder="请选择消息通道" clearable>
            <el-option
              v-for="dict in dict.type.sms_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择收件人" prop="smsReceiverIds">
          <el-tag
            v-for="tag in receivertags"
            :key="tag.name"
            closable
            :type="tag.type"
            @close="handleReceiverClose(tag)" style="margin-right: 5px">
            {{tag.name}}
          </el-tag>
          <el-button
            :name="buttonName"
            size="mini"
            type="text"
            icon="el-icon-message"
            @click="handleReceiverList"
          >{{ buttonName }}</el-button>
        </el-form-item>
        <el-form-item label="" prop="">
          <el-button type="primary" size="mini" @click="selectRecipint">选择收件人</el-button>
        </el-form-item>
        <el-form-item label="选择消息模版"  prop="smsTemplateIds">
          <el-tag
            v-for="tag in templatetags"
            :key="tag.name"
            closable
            :type="tag.type"
            @close="handleTemplateClose(tag)" style="margin-right: 5px">
            {{tag.name}}
          </el-tag>

        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" size="mini" @click="selectTemplate">选择模版</el-button>
        </el-form-item>
        <el-form-item label="发送时间" prop="sendDate">
          <el-radio-group v-model="form.startAt" @change="onRadioChange">
            <el-radio label="immediately">
              立即发送
            </el-radio>
            <el-radio label="regulartime">
              定时发送
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item >
          <el-date-picker clearable
                          v-model="sendDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择日期">
          </el-date-picker>
          <el-time-picker  arrow-control
                           v-model="sendTime"
                           value-format="HH:mm:ss"
                           placeholder="选择时间">
          </el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 消息模版选择界面 -->
    <el-dialog :title="title2" :visible.sync="open2" width="1000px" append-to-body>
      <el-form :model="queryParams2" ref="queryForm2" size="small" :inline="true" v-show="showSearch2" label-width="120px">
        <el-form-item label="创建时间起" prop="startTime">
          <el-date-picker clearable
                          v-model="queryParams2.startTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建时间止" prop="endTime">
          <el-date-picker clearable
                          v-model="queryParams2.endTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择任务启动时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="模版名称" prop="templateName">
          <el-input
            v-model="queryParams2.templateName"
            placeholder="请输入模版名称"
            clearable
            @keyup.enter.native="handleQuery2"
          />
        </el-form-item>
        <el-form-item label="模版ID" prop="templateId">
          <el-input
            v-model="queryParams2.templateId"
            placeholder="请输入模版ID"
            clearable
            @keyup.enter.native="handleQuery2"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery2">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery2">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading2" :data="HwSmsTemplateResp" @selection-change="handleSelectionChange2">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="模版名称" align="left" prop="template_name" show-overflow-tooltip/>

        <el-table-column label="模版主键ID" align="left" prop="id" show-overflow-tooltip/>
        <el-table-column label="模版ID" align="left" prop="template_id" show-overflow-tooltip />
        <el-table-column label="所属应用" align="left" prop="app_name" width="110"/>
        <el-table-column label="所属签名" align="left" prop="app_name" v-if="false" />
        <el-table-column label="模版类型" align="left" prop="template_type" width="100">
          <template slot-scope="scope">
            {{ scope.row.template_type == 1 ? '普通短信' : scope.row.template_type == 2 ? '智能短信' : scope.row.template_type }}
          </template>
        </el-table-column>
        <el-table-column label="模版内容" align="left" prop="template_content" show-overflow-tooltip/>
      </el-table>

      <pagination
        v-show="total2>0"
        :total="total2"
        :page.sync="queryParams2.pageNum"
        :limit.sync="queryParams2.pageSize"
        @pagination="getListTemplate"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 收件人界面 -->
    <el-dialog :title="title4" :visible.sync="open4" width="1000px" append-to-body>
      <el-table v-loading="loading4" :data="receiverList">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标签" align="left">
          <template slot-scope="scope">
            <el-tag style="font-size: 12px; display: inline-block;margin-right: 10px; margin-bottom: 5px;" size="small">
              {{ scope.row.receiverLableIdName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="收件人名称" align="center" prop="receiverName" />
        <el-table-column label="收件人电话" align="center" prop="receiverTel" />
      </el-table>
    </el-dialog>

  </div>
</template>

<script>


export default {
  name: "Smstask",
  dicts: ['task_state','sms_type'],
  data() {
    return {
      buttonName:'查看(0)',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading2: true,
      // 选中数组
      ids2: [],
      // 非单个禁用
      single2: true,
      // 非多个禁用
      multiple2: true,
      // 遮罩层
      loading4: true,
      // 选中数组
      ids4: [],
      // 非单个禁用
      single4: true,
      // 非多个禁用
      multiple4: true,
      // 显示搜索条件
      showSearch: true,
      //showSendTime: false,
      fromGroup: [],
      // 总条数
      total: 0,
      // 总条数
      total2: 0,
      total4: 0,
      //发送时间
      sendDate:new Date(),
      //发送时间
      sendTime:new Date(),
      // 消息群发任务表格数据
      smstaskList: [],
      // 会员列表表格数据
      memberList: [],
      receivertags: [],
      templatetags: [],
      materialList: [],
      templateList: [],
      receiverList: [],
      labelgroupList: [], //切换标签时，显示用
      checkedCities: [],
      HwSmsTemplateResp:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title2: "",
      // 是否显示弹出层
      open2: false,
      title4: "",
      // 是否显示弹出层
      open4: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dateCreated: null,
        dateUpdated: null,
        jobName: null,
        smsContent: null,
        smsHtml: null,
        smsSubjecte: null,
        enableFlag: null,
        param: null,
        startAt: null,
        endAt: null,
        memberId: null,
        createdId: null,
        createdName: null
      },
      // 查询参数
      queryParams2: {
        offset: 0,
        limit: 2000,
        starTime: null,
        templateId: null,
        endTime: null,
        templateName: null,
        templateType: null,
        flowStatus: null,
        hasVariable: null,
      },
      showSearch2: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        jobName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        smsType: [
          { required: true, message: "消息通道不能为空", trigger: "blur" }
        ],
        smsSubjecte: [
          { required: true, message: "消息主题不能为空", trigger: "blur" }
        ],
        smsReceiverIds: [
          { required: true, message: "收件人不能为空", trigger: "blur" }
        ],
        smsTemplateIds: [
          { required: true, message: "消息模版不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getLabelList();
    this.getListTemplate();
    this.getGroups();
  },
  methods: {
    /** 查询消息群发任务列表 */
    getList() {
    },
    //查询标签组
    getLabelList() {
    },
    getReceiverList() {
    },
    getListTemplate()
    {
      this.queryParams2.hasVariable="No";
      this.queryParams2.flowStatus="Adopted";
    },
    getGroups() {
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dateCreated: null,
        dateUpdated: null,
        jobName: null,
        smsType: null,
        smsContent: null,
        smsHtml: null,
        smsSubjecte: null,
        enableFlag: null,
        param: null,
        startAt: null,
        endAt: null,
        memberId: null,
        createdId: null,
        smsReceiverIds: [],
        smsTemplateIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleReceiverClose(tag) {
      this.receivertags.splice(this.receivertags.indexOf(tag), 1);
    },
    handleTemplateClose(tag) {
      this.templatetags.splice(this.templatetags.indexOf(tag), 1);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加消息群发任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSmstask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改消息群发任务";
      });
    },
    /**
     * @param {date} time 需要转换的时间
     * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
     */
    formatTime(time, fmt) {
      if (!time) return '';//没传时间返回空
      else {
        const date = new Date(time);
        const o = {
          'M+': date.getMonth() + 1,//月
          'd+': date.getDate(),//日
          'H+': date.getHours(),//时
          'm+': date.getMinutes(),//分
          's+': date.getSeconds(),//秒
          'q+': Math.floor((date.getMonth() + 3) / 3),//月+3/3
          S: date.getMilliseconds(),//返回时间的毫秒
        };
        if (/(y+)/.test(fmt))//匹配1个到多个y
          //这一步把年转换完毕
          fmt = fmt.replace(
            RegExp.$1,//拿到y+匹配到的第一个分组
            (date.getFullYear() + '').substr(4 - RegExp.$1.length)
          );
        //这一步把生下的格式继续匹配转换
        for (const k in o) {
          if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length === 1
                ? o[k]
                : ('00' + o[k]).substr(('' + o[k]).length)
            );
          }
        }
        return fmt;
      }
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.sendDate);
      this.form.startAt=this.formatTime(this.sendDate,"yyyy-MM-dd") + " "+this.formatTime(this.sendTime,"HH:mm:ss");
      this.form.memberId=this.ids2.toString();
      this.form.status=0;
      console.log(this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSmstask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSmstask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除消息群发的数据项？').then(function() {
        return delSmstask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('scrm/smstask/export', {
        ...this.queryParams
      }, `smstask_${new Date().getTime()}.xlsx`)
    },
    selectRecipint() {
      if (this.receivertags  != null) {
        this.receivertags.forEach(el1 => {
          this.checkedCities.push(el1.lCodeId);
        });
      }
      debugger;
      this.form.labelsbq = this.checkedCities;//给form赋值，防止保存时出错
      this.$refs.selectlab.show1();
      this.checkedCities = []; //这个放上面会为空？奇怪 或者赋值后延时执行打开窗口也可以
    },
    selectTemplate() {
      this.loading2 = false;
      this.open2 = true;
      this.title2 = '消息模版选择';
    },
    handleReceiverList()
    {
      this.loading4 = false;
      this.open4 = true;
      this.title4 = '收件人列表';
      this.getReceiverList();
    },
    handleStartTask(row) {
      this.reset();
      const id = row.id || this.ids
      getSmstask(id).then(response => {
        this.form = response.data;
        if (this.form.enableFlag == 1) {
          this.$modal.msgError("任务已启动，不能执行启动操作!");
        }else {
          startSmsTask(this.form).then(response => {
            this.$modal.msgSuccess("启动成功");
            this.getList();
          });
        }
      });
    },
    //保存标签
    savebq(value,val2) {
      console.log("savebq:" + value);
      console.log("savebq:" + val2);
      this.checkedCities=value;
      this.receivertags = val2;
      this.form.smsReceiverIds = value;
    },
    onRadioChange(val) {
      //val = val.toString();
      //this.sendTime =new Date();
      //this.sendDate = new Date();
      //if (val == "regulartime") {
      //  this.showSendTime = true;
      //} else if (val == "immediately") {
      //  this.showSendTime = false;

     // }
    },
    handleShowRecord(row) {
      const ids = row.id || this.ids;
      this.$emit('updateActiveName', 'smsrecord',ids);

    },
    /** 搜索按钮操作 */
    handleQuery2() {
      this.queryParams2.pageNum = 1;
      this.getListTemplate();
    },
    /** 重置按钮操作 */
    resetQuery2() {
      this.resetForm("queryForm2");
      this.handleQuery2();
    },
    // 多选框选中数据
    handleSelectionChange2(selection) {
      this.ids2 = selection.map(item => item.id)
      this.single2 = selection.length !== 1
      this.multiple2 = !selection.length;
      console.log("selection:"+selection);
      let _targetArr = []
      // 遍历已选择数据id
      selection.map(dat=>{

        let obj = {};
        obj['id'] = dat['id'];
        obj['name'] = dat['template_name'];
        _targetArr.push(obj);
      })
      this.templatetags = _targetArr;
      this.form.smsTemplateIds = this.ids2;
      console.log("templatetags:"+this.templatetags.toString());
    },
    /** 提交按钮 */
    submitForm2() {
      this.open2=false;
    },
    cancel2(){
      this.open2=false;
      this.ids2 = [];
      this.single2 = [];
      this.multiple2 = [];
    },
  }
};
</script>
